package com.itheima.auth.filter;

import com.itheima.utils.JwtTokenUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String TOKEN_HEADER = "Authorization";

    @Resource
    private PasswordEncoder passwordEncoder;

    private Map<String, Map<String,String>> users = new HashMap<>();

    private boolean inited = false;

    private void initUsers(){
        if(inited == false){
            Map<String,String> user1 = new HashMap<>();
            user1.put("username","user1");
            user1.put("password",passwordEncoder.encode("123456"));
            user1.put("authority","ROLE_USER1,user1,search_checkitem");

            Map<String,String> user2 = new HashMap<>();
            user2.put("username","user2");
            user2.put("password",passwordEncoder.encode("000000"));
            user2.put("authority","ROLE_USER2");

            users.put("user1",user1);
            users.put("user2",user2);
            inited = true;
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(TOKEN_HEADER);
        try {
            if(token != null){
                initUsers();
                //jwt解密，拿到当前登入用户名
                String username = JwtTokenUtil.parseToken(token);

                //这块的查询可以通过redis缓存查
                Map<String,String> myUser = users.get(username);

                //模拟数据库查询
                User user = new User(username,myUser.get("password"), AuthorityUtils
                        .commaSeparatedStringToAuthorityList(myUser.get("authority")));

                //往下传递身份的具体user
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                //往下传递当前登入后的身份 ThreadLocal
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //过滤器放行
            filterChain.doFilter(request, response);
        }
    }

}
